/**
 * 
 */
package org.vidyakiran.app.server.dao.util;

import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;

import javax.persistence.EntityManager;

import org.springframework.util.Assert;

import com.google.appengine.api.datastore.Key;

/**
 * @author Harpreet
 *
 */
public class DatabaseUtils {

	/** Updates the timestamp for creation date and last modified date. It 
	 * checks for the Id field and if the value is NULL, then only the creation date 
	 * is updated.
	 * @param obj The entity object to update
	 */
	public static void updateTimestamps(Object obj) {
		Method method;
		Date today = Calendar.getInstance().getTime();
		try {
			//Get the primary key and see if its null
			method = obj.getClass().getDeclaredMethod("getId");
			Key id = (Key) method.invoke(obj);
			if(id == null) {
				method = obj.getClass().getDeclaredMethod("setCreationDate", Date.class);
				method.invoke(obj, today);
			}
			method = obj.getClass().getDeclaredMethod("setLastModifiedDate", Date.class);
			method.invoke(obj, today);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**Starts the Transaction. If the entity manager is null, then gets the manager from the Factory.
	 * @param em Entity Manager instance
	 * @return The updated entity manager
	 */
	public static EntityManager startTransaction(EntityManager em) {
		if(em == null || !em.isOpen()) {
			em = EntityManagerFactoryInstance.getManager();
		}
		em.getTransaction().begin();
		return em;
	}
	
	/**Checks and see if Transaction is still active, if yes then rollback is done.
	 * @param em The entity manager instance
	 */
	public static void cleanupTransaction(EntityManager em) {
		Assert.notNull(em, "Entity Manager is null");
		//In case of errors in persist or commit, rollback
		if(em.getTransaction().isActive())
			em.getTransaction().rollback();
//		em.close();
	}
}
